package com.enation.app.javashop.api.client;

import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.WebPage;
import com.enation.app.javashop.model.base.message.GoodsChangeMsg;
import com.enation.app.javashop.model.base.rabbitmq.AmqpExchange;
import com.enation.app.javashop.model.goods.dos.BrandDO;
import com.enation.app.javashop.model.goods.dos.CategoryDO;
import com.enation.app.javashop.model.goods.dos.GoodsDO;
import com.enation.app.javashop.model.goods.dos.GoodsGalleryDO;
import com.enation.app.javashop.model.goods.dto.GoodsQueryParam;
import com.enation.app.javashop.model.goods.enums.GoodsType;
import com.enation.app.javashop.model.goods.enums.QuantityLogType;
import com.enation.app.javashop.model.goods.vo.*;
import com.enation.app.javashop.model.security.ScanModuleDTO;
import com.enation.app.javashop.model.security.ScanResult;
import com.enation.app.javashop.model.trade.order.vo.OrderSkuVO;
import com.enation.app.javashop.service.goods.*;
import io.swagger.annotations.Api;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author fk
 * @version v2.0
 * @Description: 商品服务对外client
 * @date 2018/7/30 15:06
 * @since v7.0.0
 */
@Api(description = "商品相关API")
@RestController
@RequestMapping("/client/goods")
@Validated
@ApiIgnore
public class GoodsClientController {

    @Autowired
    private GoodsManager goodsManager;
    @Autowired
    private GoodsQueryManager goodsQueryManager;
    @Autowired
    private GoodsSkuManager goodsSkuManager;
    @Autowired
    private DaoSupport daoSupport;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private GoodsParamsManager goodsParamsManager;
    @Autowired
    private CategoryManager categoryManager;
    @Autowired
    private BrandManager brandManager;
    @Autowired
    private GoodsGalleryManager goodsGalleryManager;

    @GetMapping("/new")
    public List<BackendGoodsVO> newGoods(@RequestParam("length") Integer length) {

        return this.goodsManager.newGoods(length);

    }

    @PostMapping("/under")
    public void underShopGoods(@RequestParam("seller_id") Long sellerId) {

        this.goodsManager.underShopGoods(sellerId);
    }

    @PostMapping("/grade")
    public void updateGoodsGrade() {

        this.goodsManager.updateGoodsGrade();
    }

    @GetMapping("/{goods_id}")
    public CacheGoods getFromCache(@PathVariable("goods_id") Long goodsId) {

        return this.goodsQueryManager.getFromCache(goodsId);
    }

    @GetMapping("/{goods_id}/info")
    public List<Map<String, Object>> getGoods(@PathVariable("goods_id") Long[] goodsId) {
        return this.goodsQueryManager.getGoods(goodsId);
    }

    @GetMapping("/more/{goods_ids}")
    public List<GoodsSelectLine> query(@PathVariable("goods_ids") Long[] goodsIds) {

        return this.goodsQueryManager.queryGoodsLines(goodsIds, new GoodsQueryParam());
    }

    @GetMapping("/seller/{goods_ids}/check")
    public void checkSellerGoodsCount(@PathVariable("goods_ids") Long[] goodsIds) {

        this.goodsQueryManager.checkSellerGoodsCount(goodsIds);
    }

    @GetMapping("/{goods_ids}/params")
    public List<Map<String, Object>> getGoodsAndParams(@PathVariable("goods_ids") Long[] goodsIds) {

        return this.goodsQueryManager.getGoodsAndParams(goodsIds);
    }

    @GetMapping("/seller-goods")
    public List<GoodsDO> listGoods(@RequestParam("seller_id") Long sellerId) {

        return this.goodsQueryManager.listGoods(sellerId);
    }

    @GetMapping("/skus/{sku_id}")
    public GoodsSkuVO getSkuFromCache(@PathVariable("sku_id") Long skuId) {

        return this.goodsSkuManager.getSkuFromCache(skuId);
    }

    @PostMapping("/{goods_id}/comment-count")
    public void updateCommentCount(@PathVariable("goods_id") Long goodsId, @RequestParam("num") Integer num) {

        String updateSql = "update es_goods set comment_num=comment_num + ? where goods_id=?";
        this.daoSupport.execute(updateSql, num, goodsId);
        // 发送商品消息变化消息
        GoodsChangeMsg goodsChangeMsg = new GoodsChangeMsg(new Long[]{goodsId},
                GoodsChangeMsg.UPDATE_OPERATION);
        this.amqpTemplate.convertAndSend(AmqpExchange.GOODS_CHANGE, AmqpExchange.GOODS_CHANGE + "_ROUTING", goodsChangeMsg);
    }

    @PostMapping("/buy-count")
    public void updateBuyCount(@RequestBody List<OrderSkuVO> list) {
        Set<Long> set = new HashSet<>();
        for (OrderSkuVO sku : list) {
            String sql = "update es_goods set buy_count=buy_count+? where goods_id=?";
            this.daoSupport.execute(sql, sku.getNum(), sku.getGoodsId());
            set.add(sku.getGoodsId());
        }
        // 发送修改商品消息
        GoodsChangeMsg goodsChangeMsg = new GoodsChangeMsg(set.toArray(new Long[set.size()]),
                GoodsChangeMsg.UPDATE_OPERATION);
        this.amqpTemplate.convertAndSend(AmqpExchange.GOODS_CHANGE, AmqpExchange.GOODS_CHANGE + "_ROUTING", goodsChangeMsg);
    }

    @PostMapping("/quantity")
    public boolean addGoodsQuantity(@RequestParam("order_sn") String orderSn, @RequestBody GoodsQuantityVO goodsQuantity, @RequestParam("log_type") QuantityLogType logType) {

        return true;//goodsQuantityManager.addGoodsQuantity(orderSn, goodsQuantity, logType);
    }

    @PostMapping("/reduce-quantity")
    public boolean reduceGoodsQuantity(@RequestParam("order_sn") String orderSn, @RequestParam("log_type") QuantityLogType logType, @RequestBody List<GoodsQuantityVO> goodsQuantityList) {

        return true;//goodsQuantityManager.reduceGoodsQuantity(orderSn, logType, goodsQuantityList);
    }

    @GetMapping("/count")
    public Integer queryGoodsCount() {

        return goodsQueryManager.getGoodsCountByParam(null, null, null);
    }

    @GetMapping("/count/param")
    public Integer queryGoodsCountByParam(@RequestParam("status") Integer status, @RequestParam("seller_id") Long sellerId) {
        return goodsQueryManager.getGoodsCountByParam(status, sellerId, 1);
    }

    @GetMapping("/{page_no}/{page_size}")
    public List<Map> queryGoodsByRange(@PathVariable("page_no") Integer pageNo, @PathVariable("page_size") Integer pageSize) {

        StringBuffer sqlBuffer = new StringBuffer("select g.* from es_goods g where is_auth='1' order by goods_id desc");
        List<Map> goodsList = this.daoSupport.queryForListPage(sqlBuffer.toString(), pageNo, pageSize);
        return goodsList;
    }

    @GetMapping("/{goods_id}/snapshot")
    public GoodsSnapshotVO queryGoodsSnapShotInfo(@PathVariable("goods_id") Long goodsId) {

        //商品
        GoodsDO goods = this.goodsQueryManager.getModel(goodsId);
        //参数
        List<GoodsParamsGroupVO> paramList = goodsParamsManager.queryGoodsParams(goods.getCategoryId(), goodsId);
        //品牌
        BrandDO brand = brandManager.getModel(goods.getBrandId());
        //分类
        CategoryDO category = categoryManager.getModel(goods.getCategoryId());
        //相册
        List<GoodsGalleryDO> galleryList = goodsGalleryManager.list(goodsId);

        return new GoodsSnapshotVO(goods, paramList, brand, category, galleryList);
    }

    @PostMapping
    public WebPage list(@RequestBody GoodsQueryParam goodsQueryParam) {

        return goodsQueryManager.list(goodsQueryParam);
    }

    @GetMapping(value = "/categories/{id}")
    CategoryDO getModel(@PathVariable("id") Long id) {

        return categoryManager.getModel(id);
    }

    @GetMapping(value = "/template/{id}")
    public GoodsDO checkShipTemplate(@PathVariable("id") Long templateId) {
        return goodsManager.checkShipTemplate(templateId);
    }

    @GetMapping(value = "/seller/{seller_id}")
    public Integer getSellerGoodsCount(@PathVariable("seller_id") Long sellerId) {

        return goodsQueryManager.getSellerGoodsCount(sellerId);
    }


    @PostMapping(value = "/seller/{seller_id}/change-seller-name")
    public void changeSellerName(@PathVariable("seller_id") Long sellerId, @RequestParam("seller_name") String sellerName) {
        this.goodsManager.changeSellerName(sellerId, sellerName);
    }

    @PostMapping(value = "/seller/{seller_id}/change-goods-type")
    public void updateGoodsType(@PathVariable("seller_id") Long sellerId, @RequestParam("type") String type) {
        goodsManager.updateGoodsType(sellerId, type);
    }

    @GetMapping(value = "/seller/{seller_id}/point-goods")
    public List<GoodsDO> listPointGoods(@PathVariable("seller_id") Integer shopId) {
        String sql = "select * from es_goods where goods_type = '" + GoodsType.POINT.name() + "' and seller_id = ? ";

        return this.daoSupport.queryForList(sql, GoodsDO.class, shopId);
    }

    @GetMapping(value = "/{goods_ids}/goodsdos")
    public List<GoodsDO> queryDo(@PathVariable("goods_ids") Long[] goodsIds) {

        return this.goodsQueryManager.queryDo(goodsIds);
    }

    @GetMapping(value = "/seller/{seller_id}/goods-details")
    public List<Map<String, Object>> getGoodsAndParams(@PathVariable("seller_id") Long sellerId) {

        return this.goodsQueryManager.getGoodsAndParams(sellerId);
    }

    @GetMapping(value = "/category/{id}")
    public CategoryDO getCategory(@PathVariable("id") Long id) {

        return categoryManager.getModel(id);
    }

    @RequestMapping(value = "/sku/{sku_id}/db-info", method = RequestMethod.GET)
    public GoodsSkuVO getSku(@PathVariable("sku_id") Long skuId) {

        return this.goodsSkuManager.getSku(skuId);
    }

    @RequestMapping(value = "/{goods_id}/sku-list", method = RequestMethod.GET)
    public List<GoodsSkuVO> listByGoodsId(@PathVariable("goods_id") Long goodsId) {
        return goodsSkuManager.listByGoodsId(goodsId);
    }

    /**
     * 根据商家id查询出所有的商品信息
     *
     * @param sellerId 商家id
     * @return 所有的商品信息
     */
    @RequestMapping(value = "/by-seller/{seller_id}", method = RequestMethod.GET)
    public List<GoodsDO> getSellerGoods(@PathVariable("seller_id") Long sellerId) {
        return goodsQueryManager.getSellerGoods(sellerId,null);
    }

    @RequestMapping(value = "/category/{parent_id}/children", method = RequestMethod.GET)
    List<CategoryVO> listAllChildren(@PathVariable("parent_id") Long parentId) {

        return categoryManager.listAllChildren(parentId);
    }


    @RequestMapping(value = "/skus/{sku_ids}/details", method = RequestMethod.GET)
    public List<GoodsSelectLine> querySkus(@PathVariable("sku_ids") Long[] skuIds) {

        return this.goodsQueryManager.querySkus(skuIds);
    }

    @RequestMapping(value = "/sku/{sku_id}/add-exchange-script", method = RequestMethod.POST)
    public void createSkuExchangeScript(@PathVariable("sku_id") Long skuId, @RequestParam("exchange_id") Long exchangeId, @RequestParam("price") Double price, @RequestParam("point") Integer point) {
        this.goodsSkuManager.createSkuExchangeScript(skuId, exchangeId, price, point);

    }

    /**
     * 删除积分兑换商品的脚本信息
     *
     * @param skuId 商品skuID
     */
    @RequestMapping(value = "/sku/{sku_id}/del-exchange-script", method = RequestMethod.POST)
    public void deleteSkuExchangeScript(@PathVariable("sku_id") Long skuId) {

        this.goodsSkuManager.deleteSkuExchangeScript(skuId);
    }

    @RequestMapping(value = "/goods-self-operated", method = RequestMethod.POST)
    public void updateGoodsSelfOperated(@RequestParam("seller_id") Long sellerId,@RequestParam("self_operated") Integer selfOperated) {
        goodsManager.updateGoodsSelfOperated(sellerId, selfOperated);
    }

    @RequestMapping(value = "/count/page-create", method = RequestMethod.GET)
    public Integer queryGoodsCountForPageCreate() {
        return this.goodsQueryManager.getGoodsCountByParam();
    }


    @RequestMapping(value = "/sku/{sku_id}/check-exist", method = RequestMethod.GET)
    public Boolean checkExist(@PathVariable("sku_id")Long skuId) {
        return this.goodsSkuManager.checkExist(skuId);
    }

    @RequestMapping(value = "/scan-module", method = RequestMethod.POST)
    public ScanResult scanModule(@RequestBody ScanModuleDTO scanModuleDTO) {
        return this.goodsManager.scanModule(scanModuleDTO);
    }

    @RequestMapping(value = "/sku/scan-module", method = RequestMethod.POST)
    public ScanResult scanSkuModule(@RequestBody ScanModuleDTO scanModuleDTO) {
        return this.goodsSkuManager.scanModule(scanModuleDTO);
    }



    @RequestMapping(value = "/resign", method = RequestMethod.GET)
    public void reSign(){
        goodsManager.reSign();
    }



    @RequestMapping(value = "/sku/resign", method = RequestMethod.GET)
    public void reSignSku(){
        goodsSkuManager.reSign();
    }

    @RequestMapping(value = "/repair/{goods_id}", method = RequestMethod.GET)
    public void repair(@PathVariable("goods_id")Long goodsId){
        goodsManager.repair(goodsId);
    }


    @RequestMapping(value = "/sku/repair/{sku_id}", method = RequestMethod.GET)
    public void repairSku(@PathVariable("sku_id")Long skuId){
        goodsSkuManager.repair(skuId);
    }
}
